<?php

namespace App\Console\Commands;

use App\User;
use Illuminate\Console\Command;
use Mockery\Exception;

class UserLiftBan extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ban:liftBan';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '解禁用户';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 检测脚本是否重复执行
        $this->check();
        $time = time();
        try {
            //解禁
            if (!User::where('ban_status', User::BANSTATUS_OFF)->where('ban_time', '<=', $time)->update(['ban_status' => User::BANSTATUS_ON])) {
                exit('没有需要解禁的用户');
            }
            exit('解禁成功');
        } catch (Exception $e) {
            exit('解禁失败');
        }
    }

    public function check()
    {
        $file = 'ban_liftBan.lock';
        $lock_file = storage_path($file);
        if (!flock($this->fp = fopen($lock_file, 'w'), LOCK_NB | LOCK_EX)) {
            //无法取得锁就退出
            logger($this->description . ' 脚本尝试重复启动');
            die('cannot get lock，already running?');
        }
        register_shutdown_function('unlink', $lock_file);
    }
}
